package tema.pdm;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class Weather extends ListActivity implements OnItemLongClickListener, ThreadDone{
    /** Called when the activity is first created. */
    
	Context context;
    Button buton_adaugare,buton_updatare, okAdd, cancelAdd;
    OrasAdapter oras_adapter;
    Dialog dialog;
    EditText editOras;
    private final static String NOTES="notes.txt";
    int contor;
    ProgressDialog progres ;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        context = this;
    buton_adaugare = (Button) findViewById(R.id.Adauga);
    buton_updatare = (Button) findViewById(R.id.Updateaza); 
    oras_adapter = OrasAdapter.getInstance(this);
    load();
    
    progres = new ProgressDialog(context);
    progres.setMessage("Updating. Please wait...");
    
    dialog = new Dialog(context);
	dialog.setContentView(R.layout.dialog);
	dialog.setTitle("Nou Oras");
	editOras = (EditText)dialog.findViewById(R.id.EditOras);
	okAdd = (Button)dialog.findViewById(R.id.OkAdd);
	cancelAdd = (Button)dialog.findViewById(R.id.CancelAdd);
    
    buton_adaugare.setOnClickListener(new OnClickListener(){
		@Override
		public void onClick(View v) {
			editOras.setText("");
			dialog.show();
		}
    });
    
    buton_updatare.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			//Integer contor = new Integer(0);
			int i;
			contor = 0;
			progres.show();
			for(i=0;i<oras_adapter.getCount();i++)
			{
				contor++;
				Update t = new Update(0,((Oras)oras_adapter.getItem(i)).name, context);
				t.start();
			}
		}
	});
    
    
    
    okAdd.setOnClickListener(new OnClickListener()
    {
    	@Override
    	public void onClick(View v){
    		dialog.cancel();
    		progres.show();
    		Update th= new Update(1, editOras.getEditableText().toString(),context);
    		if(th.descarcare())
    			if(th.verificare())
    				if(	oras_adapter.addOras(new Oras(editOras.getEditableText().toString())) )
    					th.start();
    				else progres.dismiss();
    			else progres.dismiss();
    		else progres.dismiss();
    	}
    });
    
    cancelAdd.setOnClickListener(new OnClickListener()
    {
    	@Override
    	public void onClick(View v){
    		dialog.cancel();
    	}
    });
    
    oras_adapter = OrasAdapter.getInstance(this);
    setListAdapter(oras_adapter);
    
    getListView().setOnItemLongClickListener(this);
}

public void threadDone()
{
	contor--;
	System.out.println("contorul este "+contor);
	if(contor ==0)
		progres.dismiss();
}
    
public void onListItemClick (ListView list, View v, int position, long id)
{	
	Intent intent = new Intent(this, Descriere.class);
	intent.putExtra("nume", ((Oras)oras_adapter.getItem(position)).name);
	startActivity(intent);
}


@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
		long id) {
	AlertDialog.Builder a = new AlertDialog.Builder(this);
	final int idx = position;
	a.setMessage("Stergeti orasul?");
   a.setCancelable(false)//Nu pot apasa Back
    .setPositiveButton("Da", new DialogInterface.OnClickListener(){
		public void onClick(DialogInterface dialog, int which) {
			try{
			File f = new File(Environment.getExternalStorageDirectory() + "/Tema1PDM/"+ ((Oras)oras_adapter.getItem(idx)).name+".txt");
			f.delete();}catch(Exception e){e.printStackTrace();}
			oras_adapter.delOras(idx); //Sterg elementul din lista
		}})
	 .setNegativeButton("Anulare", new DialogInterface.OnClickListener(){//Cancel
			public void onClick(DialogInterface dialog, int which) {} })
    .show();
	
	return true;
}


public void onResume() {
	super.onResume();
	load();
}

public void onPause() {
	super.onPause();
	save();
}

void load()
{
//	return;
	if(!oras_adapter.isEmpty())return;
	try {
    	InputStream in = openFileInput(NOTES);
    	if (in != null) {
	    	InputStreamReader tmp = new InputStreamReader(in);
	    	BufferedReader reader = new BufferedReader(tmp);
	    	String str;

	    	while ((str = reader.readLine()) != null)
	    		oras_adapter.addOras(new Oras(str));
	    	in.close();

    	}
	} catch (java.io.FileNotFoundException e) {
		// that's OK, we probably haven't created it yet
	} catch (Throwable t) {
	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
	}
}

void save()
{
	try {
    	OutputStreamWriter out = new OutputStreamWriter(openFileOutput(NOTES, 0));
    	int i, n = oras_adapter.getCount();
    	String string;
    	
    	for(i=0;i<n;i++)
    	{
    		string = ((Oras)oras_adapter.getItem(i)).name;
    		out.append(string.subSequence(0, string.length()));
    		out.append('\n');
    	}
    	out.close();
	} catch (Throwable t) {
	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
	}
}


@Override
protected void onStop(){
   super.onStop();
   save();
}

}